﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XTYAPI.通讯
{
    /// <summary>
    /// 基于同步的
    /// </summary>
    public class TcpServerSync
    {
        private Socket tcpServer;
        public int MaxComCount { get; set; } = 5;
        public List<Socket> SocketList { get;  set; } = new List<Socket>();

        public event Action<Socket,bool> SocketChange;
        public bool StartListen(string ip, int port)
        {
            IPAddress iPAddress = IPAddress.Any;
            if (ip == null || ip == string.Empty || ip.Length == 0)
            {
                iPAddress = IPAddress.Any;
            }
            else
            {
                iPAddress = IPAddress.Parse(ip);
            }
            tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //tcpServer.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,2000);
            tcpServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 2000);
            IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);
            try
            {
                tcpServer.Bind(iPEndPoint);
                tcpServer.Listen(5);
                Task.Run(() =>
                {
                    ListenConnection();
                });
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
        private void ListenConnection()
        {
            while (true)
            {
                try
                {
                    Socket tcpClient = tcpServer.Accept();
                    if (SocketList.Count < MaxComCount)
                    {
                        SocketList.Add(tcpClient);
                        SocketChange?.Invoke(tcpClient,true);
                    }
                    else
                    {
                        tcpClient.Send(Encoding.ASCII.GetBytes($"Maximum connection {MaxComCount}"));
                        Thread.Sleep(3000);
                        tcpClient.Close();
                    }
                }
                catch (Exception)
                {
                    break;
                }
            }
        }
        public void CheckSocket()
        {
            for (int i = 0; i < SocketList?.Count; i++)
            {
                if (SocketList[i].Poll(10,SelectMode.SelectRead)&& SocketList[i].Available==0)
                {
                    SocketList.Remove(SocketList[i]);
                    SocketChange?.Invoke(SocketList[i],false);
                }
            }
        }
        public void SendALL()
        {
            foreach (var item in SocketList)
            {
                try
                {
                    if (item.Connected)
                    {
                        item.Send(Encoding.ASCII.GetBytes($"Send IP{((IPEndPoint)item.LocalEndPoint).ToString()}    Recive IP{((IPEndPoint)item.RemoteEndPoint).ToString()})"));
                    }
                }
                catch (Exception ex)
                {

                }

            }
        }

    }
}
